#!/usr/bin/env python
#
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import csv
import sys

# duplicating the fields in main.py
REGO = 'Vehicle Rego'
CATEGORY = 'Category'
LOCATION = 'Pick up location'
APPROVED = 'Approved for pickup'
DAMAGE = 'Damage'
OUTPUT_FIELDS = [REGO, CATEGORY, LOCATION, APPROVED, DAMAGE]

def csv_filter(src, out, header=None):
    '''Write out the 4 necessary columns in csv style.'''
    csv_reader = csv.DictReader(src, fieldnames=header)
    for row in csv_reader:
        try:
            out.writelines([','.join([row[REGO].upper(), row[CATEGORY],
                                row[LOCATION], row[APPROVED], row[DAMAGE]]),'\n'])
        except KeyError:
            print >> sys.stderr, 'key failed for line: %s' % row
    
def getfiles(files):
    '''Generate an iterator that opens thea files.'''
    for src in files:
        yield open(src)

def main():
    """Read a list of csv filenames from the cmd line, produce a csv file."""
    sys.stdout.writelines([','.join(OUTPUT_FIELDS), '\n'])
    files = getfiles(sys.argv[1:])
    for src in files:
        # look for the right header.
        for line in src:
            header = csv.reader([line]).next()
            if REGO in line:
                csv_filter(src, sys.stdout, header=header)
                break
        

if __name__ == '__main__':
    main()
